<?php

declare(strict_types=1);

namespace app\common;

use app\BaseController;
use think\facade\View;
use think\facade\Request;
use think\facade\Session;
use app\model\Admin;


class Base extends BaseController
{

    /**
     * 析构函数
     */
    public function __construct()
    {
        $this->_initialize();
    }
    /*
     * 初始化操作
     */
    protected function _initialize()
    {
        //登录验证
        $Adata = Session::get('admin_id');
        //过滤不需要登陆的行为
        if (in_array(Request::action(), array('login', 'logout'))) {
            //return;
        } else {
            if ($Adata > 0) {
                $this->check_priv($Adata); //检查管理员菜单操作权限
            } else {
                redirect('/kllxs/Login/login')->send(); //跳转登录页面
                exit;
            }
        }
    }
    public function check_priv($id)
    {
        $admin = Admin::ability($id);
        $ability = explode(',', str_replace('@', "/", $admin['ability']));
        // dump($ability);
        $thisAbility = Request::controller() . "/" . Request::action(); //当前操作方法
        // dump($thisAbility);
        $loginAbility = get_class_methods('app\admin\controller\Login');
        foreach ($loginAbility as $k => $v) {
            $arr[] = "Login/" . $v;
        }
        array_push($ability, 'Index/index'); //自定义数据添加到数组
        array_push($ability, $arr); //自定义数据添加到数组
        if ($id != 1) {
            if (in_array($thisAbility, $ability) === false) {
                // dump(json_encode(['code' => 3, 'msg' => '你没该权限，联系管理员给予权限！']));
                echo '{"code":3,"msg":"你没该权限，联系管理员给予权限！"}';
                exit;
            }
        }
        View::assign('ability', $ability);
        View::assign('UserAdmin', $admin);
    }
    public function icon()
    {
    }
    public function index()
    {
    }
    /**
     * @name 获取方法注释名
     * $model 模块名称 如：admin shop
     * $action 控制器名称
     * $function 方法名称
     */
    public function get_annotation($model, $action, $function)
    {
        $class = "app\\" . $model . "\controller\\" . $action;
        if (class_exists($class)) {
            $reflect = new \ReflectionMethod($class, $function);
            $tmp = $reflect->getDocComment();
            $flag = preg_match_all('/@name(.*?)\n/', $tmp, $tmp);
            $tmp = trim($tmp[1][0]);
            return $tmp = $tmp != '' ? $tmp : '没有设置';
        }
    }

    /**
     * @name 获取class注释名
     * $model 模块名称 如：admin shop
     * $action 模块名称
     */
    public function get_class_annotation($action, $model)
    {
        $class  = "app\\" . $model . "\controller\\" . $action;
        // return $class;
        if (class_exists($class)) {
            $class  = new \ReflectionClass($class);
            $tmp = $class->getDocComment();
            $flag  = preg_match_all('/@name(.*?)\n/', $tmp, $tmp);
            $tmp   = trim($tmp[1][0]);
            return    $tmp   = $tmp != '' ? $tmp : '没有设置';
        }
    }
}
